package com.pojo.vo;


import com.pojo.entity.SysPermission;
import com.pojo.entity.SysRole;
import com.pojo.entity.SysUser;

import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.StringUtils;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@Data
public class UserVo implements UserDetails {
    private List<String> roles;
    List<SimpleGrantedAuthority> authorities;
    List<SysRole> roleList;
    List<SysPermission> permissionList;
    SysUser user;

    public UserVo(String username) {
        var user = new SysUser();
        user.setUsername(username);
        this.user = user;
    }

    public UserVo(String username, String password) {
        var user = new SysUser();
        user.setUsername(username);
        user.setPassword(password);
        this.user = user;
    }

    public UserVo(SysUser user) {
        this.user = user;
    }

    public UserVo(SysUser user, List<SysRole> roleList, List<SysPermission> permissionList) {

        this.user = user;
        this.roleList = roleList;
        this.permissionList = permissionList;
        this.roles = roleList.stream().map(SysRole::getName).collect(Collectors.toList());
        this.authorities = permissionList.stream()
                .filter(permission -> !StringUtils.isEmpty(permission.getPermission()))
                .map(permission -> new SimpleGrantedAuthority(permission.getPermission()))
                .collect(Collectors.toList());
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return authorities.stream().map(
                authorities -> {
                    GrantedAuthority aa = () -> authorities.getAuthority();
                    return aa;

                }
        ).collect(Collectors.toList());
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getUsername();
    }

    @Override
    public boolean isAccountNonExpired() {
        return false;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return user.getStatus() == 1;
    }
}
